package com.tte.common.anno.dateConverAnno;

import com.tte.common.utils.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 第三步：拦截器
 * 核心转换实现逻辑
 * @author TTE
 */
@Aspect
@Component
public class DateFormatAspect {
    private static Logger log = LoggerFactory.getLogger(DateFormatAspect.class);

    @Pointcut("@annotation(com.tte.common.anno.dateConverAnno.NeedDateFormatConvert)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.debug("进入切面");
        //转换
        dateFormat(joinPoint);
        return joinPoint.proceed();
    }

    public void dateFormat(ProceedingJoinPoint joinPoint) {
        Object[] objects = null;
        try {
            objects = joinPoint.getArgs();
            if (objects.length != 0) {
                for (int i = 0; i < objects.length; i++) {
                    //当前只支持判断对象类型参数
                    convertObject(objects[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("参数异常");

        }
    }

    /**
     * 转换对象里面的值
     * @param obj
     * @throws IllegalAccessException
     */
    public void convertObject(Object obj) throws IllegalAccessException {

        if (Objects.isNull(obj)) {
            log.info("当前需要转换的object为null");
            return;
        }
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            boolean containFormatField = field.isAnnotationPresent(DateField.class);
            if (containFormatField) {
                //获取访问权
                field.setAccessible(true);
                DateField annotation = field.getAnnotation(DateField.class);
                String oldPattern = annotation.oldPattern();
                String newPattern = annotation.newPattern();
                Object dateValue = field.get(obj);
                if (Objects.nonNull(dateValue) && StringUtils.hasLength(oldPattern) && StringUtils.hasLength(newPattern)) {
                    String newDateValue = DateUtil.convertStr(String.valueOf(dateValue), oldPattern, newPattern);
                    if (Objects.isNull(newDateValue)){
                        log.info("当前需要转换的日期数据转换失败 dateValue = {}",dateValue.toString());
                        continue;
                    }
                    field.set(obj, newDateValue);
                }
            }
        }
    }

}